package tw.asap.plus.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import tw.asap.plus.R;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.ui.activity.MerchantActivity;
import tw.asap.plus.ui.activity.MerchantListActivity;
import tw.asap.plus.ui.activity.WebActivity;
import tw.asap.plus.utils.Utils;

/**
 * Created by Yax on 15/11/1.
 */
public class HomeAdapter extends RecyclerView.Adapter {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    private static final int TYPE_CATEGORY = 2;
    private static final int TYPE_NO_DATA = 3;

    private int currentTab = 0;
    Context context;
    RecyclerView recyclerView;
    private ArrayList<ShopIndex.ShopEntity> list = new ArrayList<>();
    private ShopIndex shopData;

    public HomeAdapter(Context context, RecyclerView recyclerView, ShopIndex shopData) {
        this.context = context;
        this.recyclerView = recyclerView;
        this.shopData = shopData;

        if (list.size() == 0) {
            list.add(new ShopIndex.ShopEntity());
            list.add(new ShopIndex.ShopEntity());
            switch (currentTab) {
                case 0:
                    list.addAll(shopData.getToplist());
                    break;
                case 1:
                    list.addAll(shopData.getNearlist());
                    break;
                case 2:
                    list.addAll(shopData.getLastlist());
                    break;
            }
        }
    }

    public void setData(ShopIndex shopData) {
        this.shopData = shopData;
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        switch (viewType) {
            case TYPE_HEADER:
                return new VHHeader(inflater.inflate(R.layout.view_ad_pager, null));
            case TYPE_ITEM:
                View itemView = inflater.inflate(R.layout.item_store, null);
                itemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                ViewHolder itemHolder = new ViewHolder(itemView);
                itemHolder.setItemClickListener(() -> {
                    if (itemHolder.getAdapterPosition() == RecyclerView.NO_POSITION) {
                        return;
                    }
                    ShopIndex.ShopEntity shopEntity = list.get(itemHolder.getAdapterPosition());
                    Intent intent = new Intent(context, MerchantActivity.class);
                    intent.putExtra("SHOP_ENTITY", shopEntity);
                    context.startActivity(intent);
                });
                itemView.setOnClickListener(itemHolder);
                return itemHolder;
            case TYPE_CATEGORY:
                View cateView = inflater.inflate(R.layout.view_category, null);
                cateView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                return new CategoryViewHolder(cateView);
            case TYPE_NO_DATA:
                View noDateView = inflater.inflate(R.layout.item_nodata, null);
                noDateView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                return new NoDataViewHolder(noDateView);

        }
        throw new RuntimeException("there is no type that matches the type " + viewType
                + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (position == 0 && holder instanceof VHHeader) {
            if (shopData != null)
                ((VHHeader) holder).setData(shopData);
        }else if(position == 2 && holder instanceof NoDataViewHolder) {
            ((NoDataViewHolder)holder).setData(currentTab);

        }else if (position > 1 && holder instanceof ViewHolder) {
            ((ViewHolder) holder).setData(list.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public int getItemViewType(int position) {
        switch (position) {
            case 0:
                return TYPE_HEADER;
            case 1:
                return TYPE_CATEGORY;
            case 2:
                if (TextUtils.isEmpty(list.get(2).getName()) && TextUtils.isEmpty(list.get(2).getAddress())) {
                    return TYPE_NO_DATA;
                } else {
                    return TYPE_ITEM;
                }
            default:
                return TYPE_ITEM;
        }
    }

    public void onTab(int which) {
        if (currentTab == which) {
            return;
        }
        list.clear();
        list.add(new ShopIndex.ShopEntity());
        list.add(new ShopIndex.ShopEntity());
        currentTab = which;
        switch (which) {
            case 0:
                if (shopData.getToplist().isEmpty()) {
                    list.add(list.get(1));
                } else {
                    list.addAll(shopData.getToplist());
                }
                break;
            case 1:
                if (shopData.getNearlist().isEmpty()) {
                    list.add(list.get(1));
                } else {
                    list.addAll(shopData.getNearlist());
                }
                break;
            case 2:
                if (shopData.getLastlist().isEmpty()) {
                    list.add(list.get(1));
                } else {
                    list.addAll(shopData.getLastlist());
                }
                break;
        }
        notifyDataSetChanged();
    }

    class VHHeader extends RecyclerView.ViewHolder {

        @InjectView(R.id.convenientBanner)
        ConvenientBanner<ShopIndex.BannerListEntity> banner;

        @InjectView(R.id.gridView)
        GridView gridView;

        @InjectView(R.id.ll_recommend_store)
        LinearLayout ll_recommend_store;

        @InjectView(R.id.ll_common_dis)
        LinearLayout ll_common_dis;

        @InjectView(R.id.ll_prefecture)
        LinearLayout ll_prefecture;

        @InjectView(R.id.middle_ad)
        LinearLayout ll_middle_ad;

        @InjectView(R.id.img_first)
        SimpleDraweeView img_first;
        @InjectView(R.id.img_second)
        SimpleDraweeView img_second;
        @InjectView(R.id.img_third)
        SimpleDraweeView img_third;


        public VHHeader(View headerView) {
            super(headerView);
            ButterKnife.inject(this, headerView);
        }

        public void setData(ShopIndex data) {
            List<ShopIndex.BannerListEntity> bannerList = data.getBanner_list();
            banner.setPages(NetworkImageHolderView::new, bannerList)
                    //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                    .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                            //设置指示器的方向
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                            //设置翻页的效果，不需要翻页效果可用不设
                    .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer).startTurning(3000l);

            if (!data.getShortcut_list().isEmpty()) {
                img_first.setImageURI(Uri.parse(data.getShortcut_list().get(0).getImg()));
                img_first.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, WebActivity.class);
                        intent.putExtra("webURL", data.getShortcut_list().get(0).getUrl());
                        context.startActivity(intent);

                    }
                });

                if (data.getShortcut_list().size() > 1) {
                    img_second.setImageURI(Uri.parse(data.getShortcut_list().get(1).getImg()));
                    img_second.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, WebActivity.class);
                            intent.putExtra("webURL", data.getShortcut_list().get(1).getUrl());
                            context.startActivity(intent);

                        }
                    });
                }
                if (data.getShortcut_list().size() > 2) {
                    img_third.setImageURI(Uri.parse(data.getShortcut_list().get(2).getImg()));
                    img_third.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, WebActivity.class);
                            intent.putExtra("webURL", data.getShortcut_list().get(2).getUrl());
                            context.startActivity(intent);
                        }
                    });
                }
            } else {
                ll_middle_ad.setVisibility(View.GONE);
            }


            SimpleGridViewAdapter adapter = new SimpleGridViewAdapter(context, data.getClass_list());
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(context, MerchantListActivity.class);
                    intent.putExtra("SCCODE", data.getClass_list().get(position).getSccode());
                    intent.putExtra("CATEGORY_NAME", data.getClass_list().get(position).getScname());
                    context.startActivity(intent);
                }
            });
        }

    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'view_category.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */
    static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @InjectView(R.id.store_image)
        SimpleDraweeView store_image;

        @InjectView(R.id.store_name)
        TextView store_name;

        @InjectView(R.id.ratingBar)
        RatingBar ratingBar;

        @InjectView(R.id.sales_volume)
        TextView sales_volume;

        @InjectView(R.id.delivery_info)
        TextView delivery_info;

        @InjectView(R.id.store_address)
        TextView store_address;

        ItemClickListener itemClickListener = null;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);
        }

        public void setItemClickListener(ItemClickListener mListener) {
            this.itemClickListener = mListener;
        }

        public void setData(ShopIndex.ShopEntity entity) {
            store_image.setImageURI(Uri.parse(entity.getLogo()));
            String shopName = entity.getName();
            if (!TextUtils.isEmpty(entity.getSubname())) {
                shopName = shopName.concat("(").concat(entity.getSubname()).concat(")");
            }
            store_name.setText(shopName);
            ratingBar.setNumStars(Integer.parseInt(entity.getScore()));
            StringBuilder sb = new StringBuilder();
            sb.append("起送 $").append(Utils.getFormatAmt(entity.getShipping_base())).append(" | ").append("配送 $")
                    .append(Utils.getFormatAmt(entity.getShipping_price())).append(" | ").append("平均")
                    .append(entity.getShipping_times()).append("分鐘");
            delivery_info.setText(sb.toString());
            double distance = Double.parseDouble(entity.getDistance());
            String distanceStr = entity.getDistance();

            if (distance < 1) {
                double d = distance * 1000;
                distanceStr = String.valueOf(d);
            } else {
                distanceStr = distanceStr.concat("km");
            }
            store_address.setText("据您".concat(distanceStr).concat("  ").concat(entity.getAddress()));
            String saleInfo = "月銷售".concat(entity.getSale_nums()).concat("份");
            sales_volume.setText(saleInfo);
        }

        @Override
        public void onClick(View v) {
            if (itemClickListener != null) {
                itemClickListener.onClick();
            }
        }
    }


    public interface ItemClickListener {
        void onClick();
    }

    class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        @InjectView(R.id.title_tab1)
        TextView titleTab1;
        @InjectView(R.id.indicator_tab1)
        View indicatorTab1;
        @InjectView(R.id.title_tab2)
        TextView titleTab2;
        @InjectView(R.id.indicator_tab2)
        View indicatorTab2;
        @InjectView(R.id.title_tab3)
        TextView titleTab3;
        @InjectView(R.id.indicator_tab3)
        View indicatorTab3;


        CategoryViewHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
            onTab(0);
        }

        @Override
        public void onClick(View v) {

        }

        @OnClick(R.id.tab1)
        protected void onTab1Click(View view) {
            titleTab1.setSelected(true);
            indicatorTab1.setVisibility(View.VISIBLE);
            titleTab2.setSelected(false);
            titleTab3.setSelected(false);
            indicatorTab2.setVisibility(View.GONE);
            indicatorTab3.setVisibility(View.GONE);
            onTab(0);
        }

        @OnClick(R.id.tab2)
        protected void onTab2Click(View view) {
            titleTab2.setSelected(true);
            indicatorTab2.setVisibility(View.VISIBLE);
            titleTab1.setSelected(false);
            titleTab3.setSelected(false);
            indicatorTab1.setVisibility(View.GONE);
            indicatorTab3.setVisibility(View.GONE);
            onTab(1);
        }

        @OnClick(R.id.tab3)
        protected void onTab3Click(View view) {
            titleTab3.setSelected(true);
            indicatorTab3.setVisibility(View.VISIBLE);
            titleTab2.setSelected(false);
            titleTab1.setSelected(false);
            indicatorTab2.setVisibility(View.GONE);
            indicatorTab1.setVisibility(View.GONE);
            onTab(2);
        }

    }

    class NoDataViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.empty_hint)
        TextView empty_hint;

        NoDataViewHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
        }

        public void setData(int currentTab) {
            switch (currentTab){
                case 0:
                    empty_hint.setText("暫無熱門店家");
                    break;
                case 1:
                    empty_hint.setText("附近暫無店家");
                    break;
                case 2:
                    empty_hint.setText("暫無最近購買店家");
                    break;
            }
        }
    }
}
